我正在尝试使用 angularjs 实现表单验证。当用户开始在表单字段中进行更改时,验证工作正常。但它不会显示任何错误消息如果单击提交而不输入任何内容。这是代码
<form name="myform" ng-submit="register(user)" >
<div class="list ">
<label class="item item-input item-stacked-label">
<span class="input-label">Name</span>
<input type="text" placeholder="John Watson" ng-model="user.name" name="user_name" required>
<span style="color:red;" ng-show="myform.user_name.$dirty&&myform.user_name.$error.required">Name required</span>
</label>
<label class="item item-input item-stacked-label">
<span class="input-label">Mobile Number</span>
<input type="tel" ng-minlength="10" maxlength="10" ng-model="user.mobileno" placeholder="77777777" name="user_mobileno" required>
<span style="color:red;" ng-show="myform.user_mobileno.$dirty&&myform.user_mobileno.$error.minlength">Please provide a valid mobileNo</span>
</label>
<label class="item item-input item-stacked-label">
<span class="input-label">Service Provider</span><br><br>
<select class="clearfix" style="width:100%; height:30px;" ng-model="user.svp_name" name="user_svp_name" required>
<option value="">Select one </option>
<option value="xxxx">xxxx</option>
<option value="xxxx">xxx</option>
</select><br><br>
<span style="color:red;" ng-show="myform.user_svp_name.$dirty&&myform.user_svp_name.$error.required">Select your service provider</span>
</label>
<label class="item item-input item-stacked-label">
<span class="input-label">Email Id</span>
<input type="email" ng-model="user.email" placeholder="john@example.com" name="user_email" required>
<span style="color:red;" ng-show="myform.user_email.$dirty&&myform.user_email.$error.email">Please Provide a valid emailId</span>
</label>
</div>
<div style="padding:0 10px;">
<input type="submit" class="button button-balanced button-block buttonradius" value="Register" />
</div><br /><br />
</form>
我已经提到了这些问题 ( AngularJS validation on submit only ), ( Form validation popup window message works only if change is made in Angularjs ) , 但没有帮助我
更新 最后我找到了一个解决方案,但它没有像我预期的那样工作。这些是更改
<span style="color:red;" ng-show="submitted&&myform.user_name.$error.required">Name required</span>
<input type="submit" ng-click="submitted=true" class="button button-balanced button-block buttonradius" value="Register" />
但仅适用于name
和serviceprovider
字段(如果在未输入任何内容的情况下单击提交则显示错误消息),不适用于其他两个字段(mobileno、email)。
最佳答案
<span style="color:red;" ng-show="myform.user_name.$dirty&&myform.user_name.$error.required">Name required</span>
myform.user_name.$dirty
就是为什么它只显示在提交表单之前是否编辑了该字段。 $dirty
在表单字段更改之前不会被设置。
我通常做的是在我的范围上放置一个 failed
bool 值,如果表单无效,则在提交后我设置 $scope.failed = true;
。所以如果你走那条路,你会改变你的 ng-shows 到:
<span style="color:red;" ng-show="failed && myform.user_name.$error.required">Name required</span>
Controller :
$scope.register = function(user) {
if ($scope.myForm.$invalid) {
// Form is invalid
$scope.failed = true;
return;
}
delete $scope.failed;
// Other submission logic
};
关于javascript - Angularjs 表单验证仅在表单字段发生更改时才有效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26847878/