Show Error is User Enter Special Character in Textbox Angular Js - javascript

I am new to AngularJs. I have an input field and i want to show the red line error and restrict the user if user enter the special character in Textbox.
here is my Html
<input data-toggle="password" class="form-control" data-placement="after" type="password"
placeholder="User Name"
ng-model="obj.username" maxlength="16" style="text-transform: lowercase"/>
I want to restrict the user and show the error "Special Character are not allow please Try Another one" and also restrict the user.. How can i handle this in Controller

I have two possible solutions for you:
Simply use the HTML input pattern attribute, in this way you can disallow anything you want from being submitted, with native HTML validation.
<form>
<input type="text" pattern="^[a-zA-Z0-9]+$" />
<button>Submit</button>
</form>
Create a method with angular, that validates the input, on each change event.
var myApp = angular.module('myApp',[]);
myApp.controller('myController', ['$scope', function($scope) {
$scope.input = "";
$scope.error = false;
// Validation function, that sets error=true, if special chars in input.
$scope.validForm = function() {
var regex = new RegExp("^[a-zA-Z0-9]+$");
if (!regex.test($scope.input)) {
$scope.error = true;
console.log("true");
} else {
$scope.error = false;
console.log("false");
}
}
// Validation on each input change
$scope.change = function() {
$scope.validForm();
};
// Initial validation
$scope.validForm();
}]);
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div ng-app="myApp">
<form ng-controller="myController">
<!-- Input with change function that triggers validation -->
<input type="text" ng-model="input" ng-change="change()">
<!-- Error message shown if validation has errors -->
<div ng-show="error">
Error! Please fill and don't use special chars!
</div>
<!-- Disabled submit if validation has errors -->
<div>
<button ng-disabled="error">Submit</button>
</div>
</form>
</div>

Related

Make an action after two events happened - JS

Want to change submit button color after email verification and checkbox marked. Added listeners on changes and they work well. But have no idea how to find out when this events are going to happen to launch function what is going to change submit button color.
```
https://jsfiddle.net/nvologdins/brfj2xk1/
```
Here is a basic example of how to do this.
I also changed the logic a bit to update the values if the user changes them again. - #Ultimater mentioned this also.
function setupButton() {
if (validEmail && validCheckbox) {
// add/show/enable submit button or simply change the color
button.style.color = "red";
} else {
// remove/hide/disable submit button revert the changes
button.style.color = "";
}
}
form.input.addEventListener('input', (event)=>{
validEmail = emailRegex.test(event.target.value);
setupButton();
})
form.checkbox.addEventListener('change', (event)=>{
validCheckbox = event.target.checked;
setupButton();
})
I would also suggest a different method to validate the form using the Constraint Validation API.
Every element has a validity check which can easily be accessed on the form element using formElement.checkValidity() and returns true/false if all (required) fields inside the form are filled with valid values.
<form oninput="this.querySelector('#submitButton').disabled = !this.checkValidity();" onsubmit="event.preventDefault(); console.log('Submit prevented but the form seems to be valid.'); return false;">
<fieldset>
<label for="newslettermail">E-Mail</label>
<!-- you could also define a more specific pattern on the email input since email would allow foo#bar as valid mail -->
<input type="email" id="newslettermail" required>
</fieldset>
<fieldset>
<input type="checkbox" id="newsletterAcceptTos" required>
<label for="newsletterAcceptTos">I accept the Terms of Service</label>
</fieldset>
<fieldset>
<label for="textFieldWithPattern">Enter <strong>foo</strong> or <strong>bar</strong></label>
<input type="text" id="textFieldWithPattern" pattern="^(foo|bar)$" required>
</fieldset>
<button type="submit" id="submitButton" disabled>Submit</button>
<button type="submit">Force submit (will show errors on invalid input)</button>
</form>
Using this, the browser for itself checks the values if they contain a valid value.
An input[type=email] with required flag must contain a valid mail address.
A checkbox with required flag, must be checked.
An input with required and a pattern must contain a value matching the regular expression from the pattern-attribute.
No need to create extra variables and listen on two form elements separately... You can check the whole thing and update accordingly only by listening to the form element
let form = document.querySelector('form');
let input = document.getElementById('input');
let checkbox = document.getElementById('checkbox');
let submit = document.getElementById('button');
const emailRegex = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
form.addEventListener('change', (event) => {
if (checkbox.checked && emailRegex.test(input.value)) {
submit.style.color = "red";
} else {
submit.style.color = "black"
}
})
//Update
input.addEventListener('input', () => {
const changeEvent = new Event('change');
form.dispatchEvent(changeEvent)
})
<form class="main__emailAndTerms emailAndTerms">
<div class="emailAndTerms__email">
<input type="text" id="input" placeholder="Type your email address here...">
<label class="emailAndTerms__terms">I agree to <span class="terms__link">terms of service</span>
<input type="checkbox" class="terms__checkbox" id="checkbox">
<span class="terms__checkbox_custom"></span>
</label>
<button type="submit" class="email__submitButton" id="button">Submit</button>
</div>
</form>

Check Field Validity and Fields Filled Before Submission?

I am revising this question as I have changed things.
I have a form with a few fields, three of which have regex validation. I also have a function which checks if all fields are filled before the submit button is enabled, this works fine. However if the fields are filled but the invalid fields ae invalid, I can still submit the form. I want to know if I am able to merge my functions so that I can check if the fields are filled AND valid before enabling the submit button?
I have tried adding an extra && clause but this doesn't work, and I tried to implement the jQuery validate plug-in but it seemed very limited and I can't validate a postcode using it.
Here is a reduced version of my project:
// ~~~ postcode validation
function validatePostcode(postcode) {
var pcode = /^[a-zA-Z]{1,2}[0-9][0-9A-Za-z]{0,1} {0,1}[0-9][A-Za-z]{2}$/;
return pcode.test(postcode);
}
function validateP() {
var postcode = $("#postcode").val();
if (validatePostcode(postcode)) {
$("#postcode").removeClass("is-invalid");
return true;
} else {
alert('Please enter a valid postcode');
$("#postcode").addClass("is-invalid");
}
return false;
}
// ~~~ validate if form is filled completely, toggles submit & edit button
$(document).on('change keyup invalid', '.required', function(e) {
var disabled = true;
$(".required").each(function() {
var value = this.value;
if ((value) && (value.trim() != '')) {
disabled = false;
$('.toggle-disabled').prop("disabled", false);
} else {
disabled = true;
$('.toggle-disabled').prop("disabled", true);
return false;
}
});
});
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous">
<div class="col-md-6">
<input type="text" id="postcode" class="input postcode form-control required" onchange="validateP()" placeholder="Post Code" name="postcode" required>
</div>
<div class="col-md-6">
<input id="submit" class="btn btn-danger toggle-disabled" type="submit" value="Submit" disabled>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
Use below regex:
/^([0-9a-zA-Z\-\._]+)#([0-9a-zA-Z\-\._]+)\.([a-zA-Z]){2,7}$/

AngularJS: on-click if pristine OR if dirty and valid

I have an input field:
<input name="fName" type="text" class="form-control dude.firstName"
ng-trim="false"
ng-pattern="patterns.name"
ng-model="dude.firstName"
ng-model-options="{ updateOn: 'blur' }"
required>
<span class="error" ng-show="idForm.fName.$error.pattern">
Please only use letters, forward slashes, and hyphens
</span>
My requirements are this:
If user has not changed anything, it needs to run saveIdentification
If user has changed something and it is not valid, then stop and allow the form to display the message
If the user has changed something and it is valid, then run saveIdentification
<span
ng-show="localEditing.id=='SAVE'"
tabindex="0"
title="Save Changes"
class="globalIcon-save action-edit-button"
ng-click="(idForm.$pristine || (idForm.$dirty && idForm.$valid)) && saveIdentification()">
</span>
The solution above fulfills requirements 1 and 2 but not 3. It will not save if the form is changed and valid.
Please see below snippet. I just made a slight variation to your code in order to receive the form object as a parameter in the saveIdentification function.
Notice that I added an input with ng-maxlength="3" in order to reproduce the scenario where the form is invalid (When the input text is larger than 3)
When the conditions described by you are met a "ran saveIdentification!" text is logged in the browser console (devtools).
angular
.module('app', [])
.controller('myCtrl', function() {
var vm = this;
vm.wizard = {
saveIdentification: fnSaveIdentification
};
return vm.wizard;
function fnSaveIdentification(form) {debugger;
if (form && (form.$pristine || form.$valid)) { //<-- Condition here!
console.log('ran saveIdentification!');
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="myCtrl as ctrl">
<form name="myForm">
<input name="i1" type="text" ng-maxlength="3" ng-model="ctrl.input">
Submit
<!-- Display message here!! (modify as you need it)-->
<span ng-show="myForm.$invalid">Form is invalid</span>
</form>
</div>
try this:
ng-disabled="(idForm.$dirty && idForm.$invalid))"
ng-click="saveIdentification()"
>
<span ng-show="(idForm.$dirty && idForm.$invalid))">
Your error message goes here!!!
</span>

Validate input type="number" before submitting

I'm running into an interesting problem while trying to restrict user input to a number.
My HTML looks like so:
<input name="activeDate" type="number" class="form-control" ng-model="account.tag.activeDate"></input>
...and my relevant Angular controller code like so(this is inside a click handler):
tag.activeDate = moment.utc().add(tag.activeDate, tag.tagDurationType).toISOString();
Unfortunately when I click the button which submits my form and calls that click handler I get this error in my console:
[ngModel:numfmt] Expected `2015-08-27T22:09:18.919Z` to be a number
Looks like my input is checked upon submitting, when it's converted to a date within my controller. How do I limit user input to numbers without running into this?
Use ng-pattern="/^(\d)+$/" - it's simple regex expression
var app = angular.module('num', []);
app.controller('numCtrl', function($scope, $http){
$scope.digits = {};
});
angular.bootstrap(document.body, ['num']);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-controller="numCtrl">
<form class="digits" name="digits" ng-submit="getGrades()" novalidate >
<input type="text" placeholder="digits here plz" name="nums" ng-model="nums" required ng-pattern="/^(\d)+$/" />
<p class="alert" ng-show="digits.nums.$error.pattern">Numbers only, please.</p>
<br>
<input class="btn" type="submit" value="Do it!" ng-disabled="!digits.$valid" />
</form>
</body>
Select your input element, then do the following you have to look up value of number0Key and number9Key:
myElement.on("keypress", function(e) {
if (e.which < number0Key || e.which > number9Key) {
e.stopPropagation();
}
});

AngularJS validation ng-invalid class only after submit

In my from I have several inputs with validation, I need for the ng-invalid class to only be applied once the user has submitted the form.
On submit I can set a value on the scope as such...
$scope.submitForm = function () {
$scope.submited = true;
// other bits
}
... but I cant figure out how to conditionally display ng-invalid without changing the validation itself.
I am running angular 1.1.5
Demo
<input type="email" name="email" ng-model="formData.email" required />
<span ng-show="(myForm.email.$dirty || submitted) && myForm.email.$error.required">
Email is required
</span>
Use $dirty flag to show the error only after user interacted with the input:
<div ng-app>
<div ng-controller="testController">
<form name="formValidate">
<input type="text" name="testing" required ng-model="testField" ng-class="{ invalid: submitted && formValidate.testing.$invalid }"/>
<button ng-click="test()">Test</button>
</form>
</div>
</div>
<script>
var app = angular.module('', []);
function testController($scope)
{
$scope.submitted = false;
$scope.test= function()
{
$scope.submitted = true;
console.log($scope.formValidate.$invalid);
}
}
</script>
<style>
.invalid
{
border:1px solid red;
}
</style>
For custom errors I suggest to use the $setValidity method within each field.
$scope.formName.fieldName.$setValidity('custom_error_name', true);
so you will have more control over the css part too, because this kind of workflow will create also a custom class inside your field like "ng-custom_error_name" so you can deal with that.

Categories

Resources