Jquery Error validation insert div using after() but cannot remove - javascript

I want to show error validation messages next to the textbox. For that, I have used after() function and inserted a div. But the div gets appended again and again whenever the field is invalid. I just want it once. Can anybody help me with it?
Here's my code:
$(document).ready(function()
{
$("#name").blur(function()
{
var name = $("#name").val();
var txt= /^[A-Za-z\s]+$/i ;
if((txt.test(name) != true))
{
$("#name").after('<div id="one" style="color:#00aaff;">Invalid Name</div>');
$("#one").empty();
}
else
{
$("#one").remove();
}
});
});

You could use HTML 5 field's validity which is the standard.
<input type="text" pattern="[a-zA-Z]+"
oninvalid="setCustomValidity('Your error message here')"
onchange="setCustomValidity('')" />

You should use additional variable to store your state. Try this logic.
$(document).ready(function() {
var flag = false;
$("#name").blur(function() {
var name = $("#name").val();
var txt = /^[A-Za-z\s]+$/i;
if (!txt.test(name) && !flag) {
$("#name").after('<div id="one" style="color:#00aaff;">Invalid Name</div>');
flag = true;
}
else if (flag && txt.test(name)) {
flag = false
$("#one").remove();
}
});
});

Related

JS Validation Function with 3 arguments(//selector,message,validation function for specific input)

I need to implement code which should add eventlistener and on change event check if the form is valid and add the message
let validate = function(element, info, functionValidate) {
let htmlTag = document.querySelector('fieldElem');//?
htmlTag.addEventListener('change',ev=>{
let notif = document.createElement('span');
document.htmlTag.appendChild(notif);//should add span element next to input
if(fieldElem.value == '')
{
notif.style.visibility = "hidden"; //hide span if nothing happens
}
//I need to implement code which should add eventlistener and on change event check if the form is valid and add the message...
Try the following. You could also use form validation (see Form Validation Set Custom Validity for an example)
function validator(val) {
return (val != '');
}
function validateField(element, validator, message) {
var helper = document.createElement("span");
var parent = element.parentElement;
parent.appendChild(helper);
element.addEventListener('change', function() {
var val = element.value;
if (!validator(val)) {
helper.innerText = message;
} else {
helper.innerText = "";
}
});
}
validateField(document.getElementById('test'), validator, 'Wrong input');
<html>
<body>
<form>
<input id="test" type="text" placeholder="Type here"/>
</form>
</body>
</html>

How to show error message if entered value matches any one of the text?

I am working on form input field and trying to show error message when user enters any of the following text
JS01, PR03, HY79, FG36, VF42, HF23
Basically need to show error message only if user entered the above mentioned text.
<input type="text" name="prodcode" class="form-control"/>
Should we use regex to achieve this? or Any jquery/javascipt can do this?
Can anyone provide me an example?
use Jquery.inArray method to find out if the word user entered is in your defined array,
var myarray = ["JS01", "PR03","HY79","FG36", "VF42","HF23"];
var inputWord = $("input[name='prodcode']").val();
if(jQuery.inArray(inputWord , myarray) !== -1){ //if the word exits
//do what you want here
}
You can use jquery indexof method.For ex:-
a = [JS01, PR03, HY79, FG36, VF42, HF23]
var value = $('input[name="prodcode"]').val();
var indexval = a.indexOf("value" ); // this will return -1 if not found else return index
if (indexval>=0){
// code for error
}
Please Check this. The solution has been done on keydown
$(function(){
var arr = ['JS01', 'PR03', 'HY79', 'FG36', 'VF42', 'HF23'];
$('.form-control').keydown(function(){
var inputval = $('.form-control').val();
var k = $.inArray(inputval,arr);
if(k != -1){
alert('error');
}
});
});
Try with this:
var err = [ 'JS01', 'PR03', 'HY79', 'FG36', 'VF42', 'HF23' ];
$('#myInput').keyup(function (e){
console.log("ERR", err.indexOf(this.value))
if (err.indexOf(this.value) !== -1) {
$('.error').css({display: 'block'})
} else {
$('.error').css({display: 'none'})
}
})
.error{
color: red;
display:none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="myInput" type="text" name="prodcode" class="form-control"/>
<div class="error">Error</div>
You can use the includes method ( MDN includes ) and check against an array which is prefilled with invalid strings.
var valuesToCheckFor = ["JS01", "PR03","HY79","FG36", "VF42","HF23"];
if( valuesToCheckFor.includes($('input[name="prodcode"]').val()) ) {
// Do what you want.
}
P.S. you will have to add this code inside the submit handler.

change textbox value in client side and read it in server side

I have some textbox and I change the value of this textboxes in clientside (javascript) ,value was changed but when I read in server side after postback actually value not changed. my textbox isn't read only or disable.
notice that I use updatepanel and my postbacks is async.any idea to solve this issue?
update
I use this jquery to support placeholder in ie,but it cause value of my textboxes equal to placeholder value, and this conflict when my postback is async. for solving this problem I use below jquery code:
function EndRequestPostBackForUpdateControls() {
//*****************************For place holder support in ie******************************
if (runPlaceHolder != 0) {
//alert('end');
$('input, textarea').placeholder();
var $inputs = $('.placeholder');
$inputs.each(function () {
var $replacement;
var input = this;
var $input = $(input);
var id = this.id;
if (input.value == '') {
if (input.type == 'password') {
if (!$input.data('placeholder-textinput')) {
try {
$replacement = $input.clone().attr({ 'type': 'text' });
} catch (e) {
$replacement = $('<input>').attr($.extend(args(this), { 'type': 'text' }));
}
$replacement
.removeAttr('name')
.data({
'placeholder-password': $input,
'placeholder-id': id
})
.bind('focus.placeholder', clearPlaceholder);
$input
.data({
'placeholder-textinput': $replacement,
'placeholder-id': id
})
.before($replacement);
}
$input = $input.removeAttr('id').hide().prev().attr('id', id).show();
// Note: `$input[0] != input` now!
}
$input.addClass('placeholder');
$input[0].value = $input.attr('placeholder');
} else {
$input.removeClass('placeholder');
}
});
}}
function safeActiveElement() {
// Avoid IE9 `document.activeElement` of death
// https://github.com/mathiasbynens/jquery-placeholder/pull/99
try {
return document.activeElement;
} catch (err) { }}
function BeginRequestPostBackForUpdateControls() {
//*****************************For place holder support in ie******************************
if (runPlaceHolder != 0) {
// Clear the placeholder values so they don't get submitted
var $inputs = $('.placeholder').each(function () {
var input = this;
var $input = $(input);
if (input.value == $input.attr('placeholder') && $input.hasClass('placeholder')) {
if ($input.data('placeholder-password')) {
$input = $input.hide().next().show().attr('id', $input.removeAttr('id').data('placeholder-id'));
// If `clearPlaceholder` was called from `$.valHooks.input.set`
if (event === true) {
return $input[0].value = value;
}
$input.focus();
} else {
alert($(this)[0].value);
$(this)[0].value = '';
alert($(this)[0].value);
$input.removeClass('placeholder');
input == safeActiveElement() && input.select();
}
}
});
}}
$(document).ready(function () {
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_beginRequest(BeginRequestPostBackForUpdateControls);
prm.add_endRequest(EndRequestPostBackForUpdateControls);
});
I use this code to clear my textbox value before sending to server in add_beginRequest,and set value in add_endRequest (for placeholder in ie).
can anyone help solve this problem? thank you.
You changed the value of TextBox with javascript and the respective ViewState is not updated. You can use hidden field to store the value in javascript and get it in code behind.
Html
<input type="hidden" id="hdn" runat="server" />
JavaScript
document.getElementById("hdn").value = "your value";
Code behind
string hdnValue = hdn.Value;
Use hidden field to store the value, and retrieve it on the server side.

How to validate form fields with javascript objects?

I am trying to do some simple form validation using javascript object values. I know it's not "ideal", but I'm just working with a simple form that doesn't need to be iron-clad.
Please see my fiddle example: http://jsfiddle.net/6dXd7/3/
I am trying to make sure that each form field has a value. If so, set the value for myObj.fieldID to yes.
Then, when the form is submitted, check every existing myObj.XXX and be sure all their values are yes.
In my example, I am having trouble creating the object, and I don't know how to cycle through all the objects when the submit button is pressed without specifying each one by name.
Here's the code in the jsfiddle example linked to above:
<script>
$(document).ready(function () {
var myObj = {};
$("input.checkblank").blur(function () {
var inputID = $(this).attr("id");
var contents = $("input#" + inputID).val();
if (contents == "") {
$(myObj).data(inputID, "no");
} else {
$(myObj).data(inputID, "yes");
}
});
$("#verify").click(function () {
if (myObj.first && myObj.second == "yes") {
// ***** Trying to get it to scan through ALL existing myObj's and make sure all their values are "yes" *****
$('.results').text('all good');
} else {
$('.results').text('not good');
}
});
});
</script>
<input type="text" name="first" id="first" class="checkblank"><br />
<input type="text" name="second" id="second" class="checkblank">
check<br />
<p class="results"> </p>
​
​
You were storing field info in jQuery DATA and trying to check them later not in the same place...
var obj = {}
$(obj).data('a','1');
console.log(obj.a); //this will log null, cause there's no attribute 'a' in 'obj'
console.log($(obj).data('a')); //this will log '1' :]
instead do this, you should store you data in attributes from native object like this:
var obj = {}
obj['a'] = '1'; //obj.a = '1' work's too
console.log(obj.a); //now it log '1' :]
Also, your verification function is wrong.. it only check if first exists inside myObj and if second exists and is equal to "yes". So your verification function should be something like this:
$("#verify").click(function() {
var allFieldsOK = false;
for ( var field in checkedFields ) {
if ( !(allFieldsOK = checkedFields[field] ) ) break;
}
$('.results').text( allFieldsOK ? 'all good' : 'not good' );
});
Here is an update to you jsFiddle, it is working for you purpose and should work if you add more input fields with the class checkblank :]
http://jsfiddle.net/6dXd7/5/
replace this
$("#verify").click(.........});
with this
$("#verify").click(function() {
var flag=true;
$('.checkblank').each(function(){ //check all elements with class checkblank
if($(this).val().length==0) //set flag false if anyone of them is blank
flag=false;
})
if (flag) {
$('.results').text('all good');
} else {
$('.results').text('not good');
}
});
...it should work

Javascript form validation

I'm trying to have two functions checking each form input, one for onchange() and the other for onkeypress(); my reason for this would be to show if the input was valid once you leave the input field using onchange() or onblur(), and the I also wanted to check if the input field was ever empty, to remove the message indicating that bad input was entered using onkeypress() so that it would update without having to leave the field (if the user were to delete what they had in response to the warning message.)
It simply isn't working the way I intended, so I was wondering if there was something obviously wrong.
My code looks like this:
<form action="database.php" method = post>
Username
<input type='text' id='un' onchange="checkname()" onkeypress="checkempty(id)" />
<div id="name"></div><br>
.....
</form>
And the Javascript:
<script type="text/javascript">
function checkname() {
var name = document.getElementById("un").value;
var pattern = /^[A-Z][A-Za-z0-9]{3,19}$/;
if (name.search(pattern) == -1) {
document.getElementById("name").innerHTML = "wrong";
}
else {
document.getElementById("name").innerHTML = "right!";
}
}
function checkempty(id) {
var temp = document.getElementById(id).value;
if (!temp) {
document.getElementById("name").innerHTML = '';
}
}
</script>
Per your clarification in the comments, I would suggest using the onkeyup event instead of onkeypress (onkeypress only tracks keys that generate characters - backspace does not). Switching events will allow you to validate when the user presses backspace.
Here's a working fiddle.
Edit:
See this SO question for further clarification: Why doesn't keypress handle the delete key and the backspace key
This function should below should check for empty field;
function checkempty(id) {
var temp = document.getElementById(id).value;
if(temp === '' || temp.length ===0){
alert('The field is empty');
return;
}
}
//This should work for check name function
function checkname() {
var name = document.getElementById("un").value;
var pattern = /^[A-Z][A-Za-z0-9]{3,19}$/;
if (!name.test(pattern)) {
document.getElementById("name").innerHTML = "wrong";
}
else {
document.getElementById("name").innerHTML = "right!";
}
}

Categories