Angularjs Form Validation issues

Source: Internet
Author: User

Angularjs Form Validation issues

1 You can use ANGULARJS to bring your own verification, (required fields, email, url) using the method:

通过myForm.personEmail.$valid是否为true 即可判断是否通过验证。
具体是哪类错误可以通过
demo:
<input type= "text" required/> Required
<input type= "Text" ng-minlength= "5"/> min. length
<input type= "text" ng-maxlength= "/> Maximum Length"
<input type= "text" ng-pattern= "/[a-za-z]/"/> Regular expression
<input type= "Email" name= "email" ng-model= "User.email"/> e-mail
<input type= "number" name= "Age" ng-model= "user.age"/> Numbers
<input type= "url" name= "homepage" ng-model= "User.facebook_url"/>url
myForm.personEmail.$error错误信息的显示
demo:
<form Name="MyForm"> <input Name="Personemail" Required Type="Email" Ng-model= "Person.email" />  <span ng-show=> error </span><span ng-show= " Myform.personemail. $error. Required "> must be filled </span>< Span class= "PLN" > <span ng-show= "myform.personemail. $error. Email" >email address is incorrect </SPAN> 
 <input type= "Submit"  ng-disabled= "myForm. $invalid" span class= "tag" >/> to prevent form submission 
</FORM>
Block browser default validation behavior for forms: Add novalidate tags on form elements
Use the FormName.inputFieldName.property format to access the Angularjs form validation related properties.
Formname.inputfieldname. $pristine; Indicates whether the user has modified the form and has not modified true. 
Formname.inputfieldname. $dirty; modified to True
Formname.inputfieldname. $valid; verified as True
Formname.inputfieldname. $invalid; true without validation
You can set a specific style through these classes:

. Ng-valid {}
. Ng-invalid {}
. Ng-pristine {}
. Ng-dirty {}
/* Really specific CSS rules applied by angular */
. ng-invalid-required {}
. Ng-invalid-minlength {}
. Ng-valid-max-length {}

2, in addition to using Angularjs's own validation, you can use pattern matching methods (regular expressions) to resolve these situations, you can also customize the validation instructions to write or redefine the validation rules.
Demo

Angular.module ("MyTest", [])
. directive (' multipleemail ', [function ()} {
return {
Require: "Ngmodel",
Link:function (scope, element, attr, Ngmodel) {
if (Ngmodel) {
var emailsregexp =/^ ([a-z0-9!#$%& ' *+\/=?^_ ' {|} ~.-][email protected][a-z0-9-]+ (\.[ a-z0-9-]+) *[;;]?) +$/i;
}
var CustomValidator = function (value) {
var validity = Ngmodel. $isEmpty (value) | | Emailsregexp.test (value);
Ngmodel. $setValidity ("Multipleemail", validity);
return validity? value:undefined;
};
Ngmodel. $formatters. push (CustomValidator);
Ngmodel. $parsers. push (CustomValidator);
}
};
}])

<form class= "form-horizontal" role= "form" id= "Custom_form" name= "Custom_form" novalidate>
<div class= "Form-group" >
<label class= "Col-sm-2 Control-label" > Multiple email</label>

<div class= "Col-sm-10" >
<input multiple-email name= "User_email" ng-model= "User.email" required class= "Form-control" placeholder= "Custom validation, Multiple e-mail addresses to ";" or ";" Split "/>
Validation passed: {{custom_form.user_email. $valid}}
</div>
</div>
<div class= "Form-group text-center" >
<input class= "btn btn-primary btn-lg" ng-disabled= "Custom_form. $invalid" type= "Submit" value= "Submit"/>
</div>
</form>

The attributes of the Ng-model in the incoming directive:

The $viewValue property holds the actual string required to update the view.

The value $modelValue by the data model. The $modelValue and $viewvalue may be different depending on whether the $parser pipeline is operating on it.

The value of the $parsers is an array of functions, when the user interacts with the controller, and the $setviewvalue () method in Ngmodelcontroller is called one-by-one in the form of pipelining, Ngmodel values read from the DOM are The function is passed into the $parsers and is processed in turn by the parser in it.

Note: the Ngmodel. $setViewValue () function is used to set the view values in the scope.

Ngmodel. $set the Viewvalue () function can accept a parameter.

Value (String): The value parameter is the actual value that we want to assign to the Ngmodel instance.

The value of $formatters is an array of functions, where functions are invoked one at a time as the value of the data model changes in the Pipelined form. It has no effect on the $parser pipeline and is used to format and convert values to be displayed in the control that binds the value.
The value of $viewChangeListeners is an array of functions, where functions are invoked one at a time in a pipelined manner when the values in the view change. With $viewchangelisteners, similar behavior can be achieved without the use of $watch. Because the return values are ignored, these functions do not require a return value.
Using Ng-class to add classes based on criteria
Ng-class allows us to add classes based on an expression. In this case, we want to add a Has-error class to our Form-group if the state of the input box is $invalid or not pristine. The way it works is ng-class= "{<class-you-want >: <expression to be evaluated >} ".
Demo
<!-- NAME -->      < div class = "form-group" ng-class = "{ ‘has-error‘ : userForm.name.$invalid && !userForm.name.$pristine }" >          < label >Name</ label >          < input type = "text" name = "name" class = "form-control" ng-model = "user.name" required>          < p ng-show = "userForm.name.$invalid && !userForm.name.$pristine" class = "help-block" >You name is required.</ p >      </ div >           <!-- USERNAME -->      < div class = "form-group" ng-class = "{ ‘has-error‘ : userForm.username.$invalid && !userForm.username.$pristine }" >          < label >Username</ label >          < input type = "text" name = "username" class = "form-control" ng-model = "user.username" ng-minlength = "3" ng-maxlength = "8" >          < p ng-show = "userForm.username.$error.minlength" class = "help-block" >Username is too short.</ p >          < p ng-show = "userForm.username.$error.maxlength" class = "help-block" >Username is too long.</ p >      </ div >               <!-- EMAIL -->      < div class = "form-group" ng-class = "{ ‘has-error‘ : userForm.email.$invalid && !userForm.email.$pristine }" >          < label >Email</ label >          < input type = "email" name = "email" class = "form-control" ng-model = "user.email" >          < p ng-show = "userForm.email.$invalid && !userForm.email.$pristine" class = "help-block" >Enter a valid email.</ p >      </ div >Display error messages only after submitting the form

For scenarios where you want to display the error message only after the form is being submitted, you need to make some minor adjustments to the above code.

    1. You want to get rid of the ng-disabled on the Submit button, because we want the user to click Submit even if the form is not fully validated.

    2. You want to add a variable after the form has been committed. In your SubmitForm () function, simply add the $scope. Submitted = true on the line; Once the form is submitted, it saves the submitted variable with the commit value of true.

    3. Adjust the error rule from ng-class= "{' Has-error ': userform.name. $invalid &&!userform.name. $pristine}" to ng-class= "{' Has-error ': userform.name. $invalid &&!userform.name. $pristine && submitted} ". This ensures that the error message will only be displayed when the form is submitted. You may need to adjust all the other ng-class and ng-show for this variable.

The error message is now displayed only if the submitted variable is set to True.

Error message is only displayed when clicked outside the input box
The need to display an error message (also called a lost Focus blur) when clicked outside the input box is a bit more complicated than validating at commit time. Validating the form requires a custom directive when it loses focus. This is a command that allows you to manipulate the DOM.

Angularjs Form Validation issues

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.