Подтвердите номер телефона, используя angular js
Хотите установить номер телефона 10, как это сделать, используя Angular js.
Вот что я пробовал:
<form class="form-horizontal" role="form" method="post" name="registration" novalidate>
<div class="form-group" ng-class="{'has-error': registration.phone.$error.number}">
<label for="inputPhone" class="col-sm-3 control-label">Phone :</label>
<div class="col-sm-9">
<input type="number"
class="form-control"
ng-minlength="10"
ng-maxlength="10"
id="inputPhone"
name="phone"
placeholder="Phone"
ng-model="user.phone"
ng-required="true">
<span class="help-block"
ng-show="registration.phone.$error.required &&
registration.phone.$error.number">
Valid phone number is required
</span>
<span class="help-block"
ng-show="((registration.password.$error.minlength ||
registration.password.$error.maxlength) &&
registration.phone.$dirty) ">
phone number should be 10 digits
</span>
</div>
</div>
</form>
Но я не получаю ошибку проверки.
Ответы
Ответ 1
Попробуйте следующее:
<form class="form-horizontal" role="form" method="post" name="registration" novalidate>
<div class="form-group" ng-class="{'has-error': registration.phone.$error.number}">
<label for="inputPhone" class="col-sm-3 control-label">Phone :</label>
<div class="col-sm-9">
<input type="number"
class="form-control"
ng-minlength="10"
ng-maxlength="10"
id="inputPhone"
name="phone"
placeholder="Phone"
ng-model="user.phone"
ng-required="true">
<span class="help-block"
ng-show="registration.phone.$error.required ||
registration.phone.$error.number">
Valid phone number is required
</span>
<span class="help-block"
ng-show="((registration.phone.$error.minlength ||
registration.phone.$error.maxlength) &&
registration.phone.$dirty) ">
phone number should be 10 digits
</span>
Ответ 2
Отметьте этот ответ
В принципе вы можете создать регулярное выражение для удовлетворения ваших потребностей, а затем назначить этот шаблон в поле ввода.
Или для более прямого подхода:
<input type="number" require ng-pattern="<your regex here>">
Подробнее @angular docs здесь и здесь ( встроенные валидаторы)
Ответ 3
Вы также можете использовать ng-pattern, [7-9] = > номер мобильного телефона должен начинаться с 7 или 8 или 9, [0-9] = номер мобильного телефона принимает цифры, {9} номер мобильного телефона должен быть 10 цифр.
function form($scope){
$scope.onSubmit = function(){
alert("form submitted");
}
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular.min.js"></script>
<div ng-app ng-controller="form">
<form name="myForm" ng-submit="onSubmit()">
<input type="number" ng-model="mobile_number" name="mobile_number" ng-pattern="/^[7-9][0-9]{9}$/" required>
<span ng-show="myForm.mobile_number.$error.pattern">Please enter valid number!</span>
<input type="submit" value="submit"/>
</form>
</div>
Ответ 4
Вы также можете использовать ng-pattern
, и я считаю, что это будет лучшая практика. Аналогичным образом попробуйте использовать ng-message
. Посмотрите атрибут ng-pattern на следующий html. Фрагмент кода является частичным, но надеюсь, что вы его понимаете.
angular.module('myApp', ['ngMessages']);
angular.module("myApp.controllers",[]).controller("registerCtrl", function($scope, Client) {
$scope.ph_numbr = /^(\+?(\d{1}|\d{2}|\d{3})[- ]?)?\d{3}[- ]?\d{3}[- ]?\d{4}$/;
});
<form class="form-horizontal" role="form" method="post" name="registration" novalidate>
<div class="form-group" ng-class="{ 'has-error' : (registration.phone.$invalid || registration.phone.$pristine)}">
<label for="inputPhone" class="col-sm-3 control-label">Phone :</label>
<div class="col-sm-9">
<input type="number" class="form-control" ng-pattern="ph_numbr" id="inputPhone" name="phone" placeholder="Phone" ng-model="user.phone" ng-required="true">
<div class="help-block" ng-messages="registration.phone.$error">
<p ng-message="required">Phone number is required.</p>
<p ng-message="pattern">Phone number is invalid.</p>
</div>
</div>
</div>
</form>
Ответ 5
Еще более чистый и профессиональный взгляд, который я нашел, - использовать AngularUI Mask. Очень просто реализовать, и маска может быть настроена и для других входов. Тогда вам понадобится простая требуемая проверка.
https://angular-ui.github.io/
Ответ 6
<form name = "numberForm">
<div>
<input type="number"
placeholder = "Enter your phonenumber"
class = "formcontroll"
name = "numbers"
ng-minlength = "10"
ng-maxlength = "10"
ng-model="phno" required/>
<p ng-show = "numberForm.numbers.$error.required ||
numberForm.numbers.$error.number">
Valid phone number is required</p>
<p ng-show = "((numberForm.numbers.$error.minlength ||
numberForm.numbers.$error.maxlength)
&& numberForm.numbers.$dirty)">
Phone number should be 10 digits</p><br><br>
</div>
</form>
Ответ 7
Используйте ng-pattern, в этом примере вы можете проверить простой patern с 10 номерами, когда patern не соответствует, сообщение отображается, и кнопка отключена.
<form name="phoneNumber">
<label for="numCell" class="text-strong">Phone number</label>
<input id="numCell" type="text" name="inputCelular" ng-model="phoneNumber"
class="form-control" required ng-pattern="/^[0-9]{10,10}$/"></input>
<div class="alert-warning" ng-show="phoneNumber.inputCelular.$error.pattern">
<p> write a phone number</p>
</div>
<button id="button" class="btn btn-success" click-once ng-disabled="!phoneNumber.$valid" ng-click="callDigitaliza()">Buscar</button>
Также вы можете использовать другой сложный patern, например
^ +?\d {1,3}? [-.]? (? (?:\d {2,3}))? [-.]?\d\d\d [-.]?\d\d\d\d $
для более сложных телефонных номеров
Ответ 8
используйте ng-intl-tel-input для проверки номеров мобильных телефонов для всех стран. вы также можете указать страну по умолчанию.
на npm: https://www.npmjs.com/package/ng-intl-tel-input
подробнее: https://techpituwa.wordpress.com/2017/03/29/angular-js-phone-number-validation-with-ng-intl-tel-input/