Angularjs iu.mask validation input with date - javascript

im learning angular and right now i created input (type:text) which should display date, and it have ui.mask like "99/99/9999", it has validation in module to not pass (unblock button) if there is a wrong date , i mean ex: 00/00/0000 or 12/12/1700, but the input dont show red frame, it displays like it is valid format, how can i show red frame based on module validation?
HTML
<input
id="dob"
type="text"
class="form-control cell-height form-input"
ng-model="createAccount.dob"
ui-mask="99/99/9999"
placeholder="D.O.B. (mm/dd/yyyy)"
required/>
CONTROLLER
var validateDob = function () {
try {
var date = moment.utc($scope.createAccount.dob, "MM/DD/YYYY");
if ($scope.patient == null) $scope.patient = {};
if (!date.utc().isValid()) return false;
if (date.utc().date() == 0 || date.utc().year() == 0) return false;
if (date.utc().isAfter(moment().utc())) return false;
if (date.utc().isSame(moment().utc())) return false;
if (!date.utc().isAfter(moment.utc().subtract(150, 'years'))) {
return false;
}
$scope.createAccount.dateOfBirth = date.utc();//.format("YYYY/MM/DD");
return true;
}
catch (err) {
return false;
}
};

Thanks to angular documentation In order to do a custom validation, you need to create a directive, not a controller.
When the validator return a false response, angular will put an ng-invalid class to you DOM Object. It will allow you to change the border color or the style of your invalid input

there were easier way, ng-class - check if validateDob returning false, if yes, show validation frame.

Related

How to restrict date format in date field

I'm trying to implement a function that will bring up an alert box when a date in the wrong format is entered and the submit button is pressed. I have six date fields in my form.
I can't seem to find regex examples that show me how to implement the function in my field inputs only how to do the function itself. I wanted to restrict it to YYYY-MM-DD. Posting here is the last resort for me, I have looked for a long time to no avail. Please can someone help?
function validate_date() {
var date_regex = /^(0[1-9]|1[0-2])\/(0[1-9]|1\d|2\d|3[01])\/(19|20)\d{2}$/ ;
if(!(date_regex.test(testDate)))
{
alert('Wrong format!');
return false;
}
}
<input type="text" class="form-control" id="empexpiry" style="width:350px;" placeholder="Nothing on File" name="empexpiry" value=""
If I was you I would use some plugin. There are good vanilla and jQuery plugins to validate forms (e.g. Vanilla, jQuery).
But if you wanna do it by yourself:
Listen to the submit event of the form and validate all your entries using regex
The function to validate could be something like this
function isDateValid (dateStr) {
let isValid = dateStr.match(/[0-9]{4}-[0-9]{2}-[0-9]{2}/)
if (!isValid) return false
const dateObj = new Date(dateStr);
isValid = dateObj != 'Invalid Date'
return isValid
}
And your function to listen the submit could be something like this:
function validateForm (e) {
const input1 = document.getElementById("input1").text
if (!isDateValid(input1)) {
alert('invalid')
e.preventDefault()
return false
}
/* And so on */
}
I found out that the HTML5 pattern attribute was all that was required. Simple!
<input id="date" type="text" pattern="\d{4}-\d{1,2}-\d{1,2}" oninvalid="setCustomValidity('Please make sure the date follows this format: YYYY-MM-DD')" required="required"/>

Form validation. Optimize Angular ng-required expression

I'm creating a form validation and it becomes too ugly and heavy because of too many fields that need to be validated. I need to optimize it. So, I'm making required any field based on the other fields values using ng-required. When the user insert a value in one of the fields then the rest of them loose the required quality and the form becomes valid. So, for that I created an expression like this:
<input ng-model="field.one" ng-required="
!field.two &&
!field.three &&
!field.four &&
!field.five &&
!field.six &&
... &&
!filed.twenty"/>
<input ng-model="field.two" ng-required="
!field.one &&
!field.three &&
!field.four &&
!field.five &&
!field.six &&
... &&
!filed.twenty"/>
So, I intend to move the required expression in the controller or where you think it should be moved in order to optimize and organize the code. I was thinking to encapsulate it in a function inside of controller but I didn't succeed. I tried something like this:
VIEW
<input ng-model="field.one" ng-required="myFunc(field.one)"/>
CTRL
$scope.myFunc = function(modelField){
anything I tried in this fn I didn't make it to work syncronized with
the field models, updating their models based on user interaction :)
}
Please, is there someone that has an ideea how should be done? Thanks.
I would prefer one scope variable which is bound to all input field's ng-required attribute. And on change of any of the input field toggle this variable.
http://plnkr.co/edit/PVXVD9RKM8cMwCVjFA7c?p=preview
<input type="text" ng-change="onChange(userName1, 'name1')" name="name1" ng-model="userName1" ng-required="required">
<input type="text" ng-change="onChange(userName2, 'name2')" name="name2" ng-model="userName2" ng-required="required">
$scope.required = true;
$scope.userNames = [];
$scope.onChange = function(val, name) {
if (val) {
if ($scope.userNames.indexOf(name) == -1) {
$scope.userNames.push(name);
}
$scope.required = false;
} else {
if ($scope.userNames.indexOf(name) !== -1) {
$scope.userNames.splice($scope.userNames.indexOf(name), 1);
}
if ($scope.userNames.length === 0) {
$scope.required = true;
}
}
}

Validation in jQuery and redirect new page with error fields

How to validate my all fields by using jquery ?
if validation fails,i want to redirect to new page and list out all validation failed fields.If it is success i will do insert operation.
Example
<input class="textbox validate"type="text">
<input class="textbox validate"type="text">
//validate the all the field with having "validate" class
$(".validate").each
I am using MVC-3 but i want to do in custom j-query logic. I am a new person in j-query.
Thanks in advance !
Assuming you have a single function for validation:
function validate (text) {
...
return true; //or false
}
Then one thing you can do:
var validationErrors = [],
errorPageURL = "BASE URL for your error page";
$(".validate").each(function (index, element) {
if (!validate(element.val()) {
validationErrors.push($(element).id);
}
});
if (validationErrors.length === 0) {
//Do your input magic
} else {
window.location.replace(errorPageURL + "?errors=" + encodeURI(JSON.stringify(validationErrors)));
}
A few reference links:
jQuery val method
jQuery each method
About client-side redirects (with/without jQuery)

Javascript: Field validation

so i have been looking all over the internet for some simple javascript code that will let me give an alert when a field is empty and a different one when a # is not present. I keep finding regex, html and different plugins. I however need to do this in pure Javascript code. Any ideas how this could be done in a simple way?
And please, if you think this question doesn't belong here or is stupid, please point me to somewhere where i can find this information instead of insulting me. I have little to no experience with javascript.
function test(email, name) {
}
Here if you want to validate Email, use following code with given regex :
<input type="text" name="email" id="emailId" value="" >
<button onclick = "return ValidateEmail(document.getElementById('emailId').value)">Validate</button>
<script>
function ValidateEmail(inputText){
var mailformat = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if(inputText.match(mailformat)) {
return true;
}
else {
alert("You have entered an invalid email address!");
return false;
}
}
</script>
Or if you want to check the empty field, use following :
if(trim(document.getElementById('emailId').value)== ""){
alert("Field is empty")
}
// For #
var textVal = document.getElementById('emailId').value
if(textVal.indexOf("#") == -1){
alert(" # doesn't exist in input value");
}
Here is the fiddle : http://jsfiddle.net/TgNC5/
You have to find an object of element you want check (textbox etc).
<input type="text" name="email" id="email" />
In JS:
if(document.getElementById("email").value == "") { // test if it is empty
alert("E-mail empty");
}
This is really basic. Using regexp you can test, if it is real e-mail, or some garbage. I recommend reading something about JS and HTML.
function test_email(field_id, field_size) {
var field_value = $('#'+field_id+'').val();
error = false;
var pattern=/^([\w-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
if(!pattern.test(field_value)){
error = true;
$('#'+field_id+'').attr('class','error_email');
}
return error;
}
This will check for empty string as well as for # symbol:
if(a=="")
alert("a is empty");
else if(a.indexOf("#")<0)
alert("a does not contain #");
You can do something like this:
var input = document.getElementById('email');
input.onblur = function() {
var value = input.value
if (value == "") {
alert("empty");
}
if (value.indexOf("#") == -1) {
alert("No # symbol");
}
}
see fiddle
Although this is not a solid soltuion for checking email addresses, please see the references below for a more detailed solution:
http://www.regular-expressions.info/email.html
http://www.codeproject.com/Tips/492632/Email-Validation-in-JavaScript
---- UPDATE ----
I have been made aware that there is no IE available to target, so the input field needs to be targeted like so:
document.getElementsByTagName("input")
Using this code will select all input fields present on the page. This is not what are looking for, we want to target a specific input field. The only way to do this without a class or ID is to selected it by key, like so:
document.getElementsByTagName("input")[0]
Without seeing all of your HTML it is impossible for me to know the correct key to use so you will need to count the amount of input fields on the page and the location of which your input field exists.
1st input filed = document.getElementsByTagName("input")[0]
2nd input filed = document.getElementsByTagName("input")[1]
3rd input filed = document.getElementsByTagName("input")[2]
4th input filed = document.getElementsByTagName("input")[3]
etc...
Hope this helps.

jQuery Validation conditional dependency: ensure text input matches value if radio button checked

I have a some form elements that follow a format like this:
<input type="radio" name="test" value="A"> <input type="text" size="3" name="weightA" id="A"><br>
<input type="radio" name="test" value="B"> <input type="text" size="3" name="weightB" id="B"><br>
I am using the jQuery Validation plugin to conduct client-side validation. What I would like to do with these fields is to ensure that the text input corresponding to the selected radio button equals 100. I have successfully implemented this on the server-side using PHP, but would like to add a JS method to give immediate feedback before the form is submitted. I have already included a jQuery range: rule to constrain user inputs in the two text fields within the numeric range [1-100].
How would I go about making this work? Would jQuery.validator.addMethod be the way to do it?
Edit: in response to Sparky's comment, I have attempted an addMethod, below:
$.validator.addMethod(
"selectWt", function(value, element) {
var selA = $('[name="test"]').val() === "A";
var selB = $('[name="test"]').val() === "B";
if (selA && ($("#A").val() !== "100")) {
return false;
} else if (selB && ($("#B").val() !== "100")) {
return false;
} else return true;
}, "Selected option must equal 100."
);
This seems to trigger the validation for #A but not #B, and the error message displayed is the one specified by the message: rule rather than the one specified by addMethod. Please bear in mind I have minimal programming background.
Try this:
DEMO: http://jsfiddle.net/maqZe/
$.validator.addMethod("selectWt", function (value, element) {
if ($(element).prev().is(':checked')) {
return ($(element).val() === 100);
} else {
return true;
}
}, "Selected option must equal 100.");
This rule can be applied generically. It simply checks to see if the radio element placed previous to element is checked. If so, it then returns true only if the text element's value is 100.
The way it's written, it only works if your type=text element immediately follows the type=radio element. It will need to be tweaked if you change the HTML arrangement.
It can also be made more flexible by passing in the 100 value as a parameter.
DEMO: http://jsfiddle.net/NFJUN/
$.validator.addMethod("selectWt", function (value, element, param) {
if ($(element).prev().is(':checked')) {
return ($(element).val() === param);
} else {
return true;
}
}, "Selected option must equal {0}.");
...
$('#myform').validate({ // initialize the plugin
rules: {
myfield: {
selectWt: 100 // use a parameter instead of "true"
},
}
});

Categories

Resources