In this post I would like to show how you can validate forms in Umbraco, and ASP.Net in general, using Angular (version 1).
- At first we will create regular form in Umbraco
- Then we will attach a function to the form submit event
- At the end we will validate the fields and show error messages
Let’s use standard Umbraco login form:
As you can see, I’ve removed standard Umbraco RequireJs and added Angular scripts in this place. Next step is modifying default BeginUmbracoForm call by adding htmlAttributes object. What we need here is: novalidate option, to disable HTML5 validation, name parameter, to access form inside Angular controller scope and ng-submit set to our function, which will be called on form submit.
To allow fields validation, each of them needs to have ng-model applied, otherwise it won’t work correctly.
Next point of interest are validation messages. As you can see I’ve placed them directly in HTML, but there is no reason to not make them more generic and store them inside scripts file. Validation messages are displayed only when validation flag is set to true and when specific error occurs. E.g. if we set filed required attribute, we can then check if this field is valid by calling formName[‘filedName’].$error.required. Keep in mind that we are accessing each form field by its name, not by model. It’s very similar with ng-pattern, if it’s set to some regex we can then check it by calling formName[‘filedName’].$error.pattern. More details about possible ways to validate form in Angular you can find in Angular official documentatnion.
Let’s now take a look at scripts file:
What is worth to mention here is loginFormSubmit function. Inside this function I’m setting validation flag to true and prevent form submiting if there are any validation errors. This is the place where you can make additional checks, e.g. check if password and password confirmation matches each other on registration page.
In this file you can also find emailRegex. This is the Regular Expression I’m using to validate email adresses. It can be also placed directly in HTML file, but I prefer to store it in scripts, in case I would need to reuse it somewhere.
That’s all, simple example, how to validate form in Umbraco using Angular. In exactly same way you can validate forms in all ASP.Net MVC applications, only difference is using BeginForm instead of BeginUmbracoForm.
I will be really thankful for any feedback, so if you have something to add or need some more explanations, just let me know in comments below.