Trouble adding data-parsley-pattern programmatically - javascript

I'm using Parsley, and it's great! I want to add different validators programmatically, depending on locale, using javascript/JQuery. When I hard-code like so:
<input type="text" id="billingPostalCode"
name="userInput_billingPostalCode"
value='<c:out value="${param.billingPostalCode}"></c:out>'
class="form-control" required=""
data-parsley-pattern="^\d{5}(?:[-\s]\d{4})?$"
data-parsley-error-message="Valid Zip/Postal Code Required"></input>
it works great. However, when I try to add it programmatically, it doesn't. I have this in a .jsp file:
<input type="text" id="billingPostalCode"
value='<c:out value="${param.billingPostalCode}"></c:out>'
class="form-control" required=""
data-parsley-error-message="Valid Zip/Postal Code Required">
</input>
And this in .js:
$('#billingPostalCode').attr('data-parsley-pattern', "^\d{5}(?:[-\s]\d{4})?$");
The attribute gets added (I can inspect the element and see it), but it doesn't validate correctly (it sees valid input as invalid). I have tried placing the JQuery code both before and after attaching parsley to the form:
[here...]
$('#paymentInfoForm').parsley( ... );
[and here...]
I have also experimented with the regex, anchored and unanchored, simplified versions, etc. But like I said, the regex works perfectly when it's hard-coded.
Could there be some interference with JSP? Am I missing something? Thanks in advance.

I worked around this by using [0-9] instead of /d in my regular expression. It does seem to be a bug, though. This works as expected:
$('#billingPostalCode').attr('data-parsley-pattern', "[0-9]{5}(?:[-\s][0-9]{4})?");
but the following code not won't validate anything, and will even break hard-coded validation:
$('#billingPostalCode').attr('data-parsley-pattern', "\d{5}(?:[-\s]\d{4})?");
The problem must be specific to javascript, since it works when hard-coded into the jsp file.

Related

MaskedPassword.js: How to get actual value (plain text) in JS

I'm using MaskedPassword.js to mask a password field in my form as demonstrated below:
<input type="password" id="pwd" name="pwd" autocomplete="off">
<script type="text/javascript">
new MaskedPassword(document.getElementById("pwd"), '\u25CF');
</script>
I'm trying to retrieve the plain text value of this password field using Javascript but unable to do so.
I've already tried the following:
document.getElementById("pwd").value
document.getElementById("pwd").text
document.getElementById("pwd").defaultValue
document.getElementById("pwd").innerHTML
Can anyone help me get the actual value?
Assuming you are using a version of the code in this post (possibly this implementation), I believe you would find it in the hidden field that is generated by the code, like so:
document.getElementById('pwd-unmasked').value
After struggling a couple of hours, I finally found out the following fix that worked for me:
document.getElementById('pwd')._realfield.value
Posting it here might help someone else.

Regex problems with angularjs

I am trying to use a regular expression to validate an email address. It does not seem to be doing any validation at all. When I load the page the Submit button is disabled because of the $pristine but as soon as I type a letter the button becomes enabled. Also I am aware that the regex is only accepting upper-case at the moment. The following code is my form:
<form name="myForm" ng-hide="email" >
Insert Email : <br/>
<input type="text" name="email" ng-pattern="/^[A-Z0-9._%+-]+#[A-Z0-9.-]+\\.[A-Z]
{2,4}$/" ng-model="insert_email" required>
<br/>
<button ng-hide="email"
type="submit"
ng-disabled="myForm.email.$pristine || myForm.email.$invalid">Submit</button>
</form>
I am not sure but I think the problem may lie with the regex itself.
take out the email in myForm.email.$pristine and in myForm.email.$invalid
to look like:
myForm.$pristine
and
myForm.$invalid
also try with ng-required instead of required
It seems to be two things. It looks like the ng-pattern expects an expression instead of a string attribute.
So you need to wrap it in a string if you want to use an inline expression.
Like so:
ng-pattern="'^[A-Z0-9._%+-]+#[A-Z0-9.-]+\\.[A-Z]{2,4}$'"
Also, there seems to be some issues with your regex. I changed it to this:
ng-pattern="'^[a-zA-Z0-9._%+-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$'"
It seems to work.
Plunker Demo

Angularjs Form/Field validation using JavaScript function without directives

Is there a way to validate a field in angular without using a directive?
For example: I want to make following validation on an input field.
If field is empty we should show "Field must contain a value" message.
if field contains alpha Numeric characters we should show "Field can contain only digits".
An EVEN number - message to the user "Value must be an even number".
I want to make following validation in a call to JavaScript function.
I googled around and saw that there is a way to use ng-valid and $error , however I was not managed to make it work.
Code below is according to one of the answers I got:
<div ng-app>
<form name='theForm' novalidate>
<input type='text' name='theText' ng-model='theText' ng-pattern='/^[0-9]+$/'/>
<span ng-show='theForm.theText.$error.pattern'>Field can contain only digits</span>
<span ng-show='theText.length<1'>Field must contain a value</span>
<span ng-show='theText%2!=0&&document.getElementsByName("theText").value!=""&&!theForm.theText.$error.pattern&&!theForm.theText.$pristine'>Value must be an even number</span>
<br/><input type='submit' value='Submit' />
</form>
I want to take what inside the last [span] and put inside a JavaScript function in order to make it more generic and eventually change only JS and not the HTML when conditions are changing
Can someone please advise? a working example would be great.
I'm surprised no one has mentioned ui-validate
$scope.isOdd = function($value){
return $value % 2;
}
...
<form name="myform">
<input ng-model="myVal" name="value" required
ng-pattern="/^[0-9]*$/" ui-validate=" 'isOdd($value)' "></input>
<pre>{{myform.value.$error|json}}</pre>
</form>
Doesn't get any simpler than that, and it's PROPER AngularJS validation (not silly watches)
Here's a working demo
Take a look at the angularjs form documentation - http://docs.angularjs.org/guide/forms . In general, it is based on the HTML5 attributes like required, min, max, etc.
To get, for example, your first requirement done - "an empty field should show "Field must contain a value" message, yo uwould do something like that:
<input type="text" ng-model="user.name" name="uName" required /><br />
<div ng-show="form.uName.$invalid">
<span ng-show="form.uName.$error.required">Field must contain a value.</span>
</div>
For digits only field you can use the pattern attribute with a matching regular expression (example: http://www.wufoo.com/html5/attributes/10-pattern.html).
For even number validation, I'm not sure - I think you'd have to go with custom validation for that (meaning you'd have to create a directive) or use the pattern attribute somehow.
Last but not least - remember to add novalidate to the <form> tag. Otherwise the browser will try to validate your fields as well and you don't want that:
<form ... novalidate>
...
</form>
I know the question is old and I know you didn't want a directive but you may consider using a directive if it's "Angular" way... Well here is my Angular-Validation. I made a project on Github and I think that it just rocks compare to whatever is/was available...I based myself on the excellent Laravel PHP Framework and made it available under Angular... It is so crazy simple, you need 2 lines 1 line of code, 1 line for the input, 1 line for error display, that's it... never more and never less!!! Enough said, let's give some examples:
<!-- example 1 -->
<label for="input1">Email</label>
<input type="text" validation="email|min_len:3|max_len:25|required" ng-model="form1.input1" name="input1" />
<!-- example 2 -->
<label for="input2">Alphanumeric + Exact(3) + required</label>
<input type="text" validation="alpha|exact_len:3|required" ng-model="form1.input2" name="input2" />
So I can define whatever amount of validation rules (already 25+ type of validators) which I want in a simple directive validation="min_len:2|max_len:10|required|integer" and the error message will always display in the next <span> Don't you guys like it already? 1 line of code for your input, 1 line of code for the error display, you can't be simpler than that...oh and I even support your custom Regex if you want to add. Another bonus, I also support whichever trigger event you want, most common are probably onblur and onkeyup. Oh and I also support multiple localization languages via JSON external files. I really added all the imaginable features I wanted into 1 crazy simple directive.
No more clustered Form with 10 lines of code for 1 input (sorry but always found that a little extreme) when the only thing you need is 2 lines, no more, even for an input with 5 validators on it. And no worries about the form not becoming invalid, I took care of that as well, it's all handled the good "Angular" way.
Take a look at my Github project Angular-Validation... I'm sure you'll love it =)
UPDATE
Another candy bonus! To make an even more smoother user experience, I added validation on timer. The concept is simple, don't bother the user while he's typing but do validate if he makes a pause or change input (onBlur)... Love it!!!
You can even customize the timer as per your liking, I've decided to default it to 1 second within the directive but if you want to customize you can call as for example typing-limit="5000" to make a 5 sec. timeout. Full example:
<input type="text" ng-model="form1.input1" typing-limit="5000" validation="integer|required" name="input1" />
<span class="validation text-danger"></span>
UPDATE #2
Also added input match confirmation validation (ex.: password confirmation), here is a sample code
<!-- input match confirmation, as for example: password confirmation -->
<label for="input4">Password</label>
<input type="password" name="input4" ng-model="form1.input4" validation="alpha|min_len:4|required" />
<label for="input4c">Password Confirmation</label>
<input type="password" name="input4c" ng-model="form1.input4c" validation="match:form1.input4,Password|required" />
UPDATE #3
Refactored the directive so that the requirement of having a <span> to display the error is unnecessary, the directive now handles it by itself, see the code change reflected on top.
DEMO
Added a live demo on Plunker
Well you can try to create a func
<span ng-show='isEven(theText)'>Value must be an even number</span>
$scope.isEven=function(data) {
if(data) {
return data%2===0
}
return true;
}
The method can either be defined on the current controller scope or on $rootScope.
Not a very angular way, as directives would be better but i think it would work.

Javascript - concatenate field value to onclick button link?

I have an issue I need to fix on an existing app that I didn't initially write. Here is a snippet of code that doesn't do what it is intended to do. What it is supposed to do is take the value of the field and upon clicking "Search", append that to the redirection to pass in the querystring to the destination page:
<form name="frm_someform">
<input type="text" name="f_date" id="f_date"/>
<input type="button" value="Search" onclick="parent.location='runreport.asp?date=' + document.frm_someform.elements['f_date'].value); + '"/>
</form>
Now, as you javascript folks can plainly see, the concatenation doesn't work. I've searched high and low for how to properly concatenate, but something isn't translating correctly (in my head). Note that if I take out the concatenation, the redirection works fine, so there is something with that causing the issue. Yes, of course in the example above, I could simply make the form submit the proper value with a real 'submit' button, but I have whittled the code down here for simplicity - it is much more complex than the example I have above.
(*Note, I successfully tested concatenation through other javascript functions, but the possibility exists that the purely inline code must be different)
Thanks in advance,
Beems
Please, try this:
<form name="frm_someform">
<input type="text" name="f_date" id="f_date"/>
<input type="button" value="Search" onclick="parent.location='runreport.asp?date='+ document.getElementById('f_date').value"/>
</form>

Long form validation in JavaScript / jQuery

I have a long long long form. It has about 200 fields. Now, about 50 fields need to be validated through JavaScript / jQuery. How can I easily validate them without a huge amount of code. I want to avoid doing this:
field1 = document.getElementById("field1").value;
if (field1 == '') {
alert ("Please enter a value for Field1");
return false
}
Is there an easier way? Thanks a lot.
Use the jquery Form validation plugin and assign the correct classes to the fields.
It's as simple as class="required" in most cases!
If you just want to check if the field is empty or not you could do something like this using jQuery:
HTML:
<form>
<input class="validate" type="text" />
<input type="text" />
<input class="validate" type="text" />
<input type="text" />
<input class="validate" type="text" />
</form>
SCRIPT:
$('.validate').each(function() { //this will get every input marked with class "validate"
if ($(this).val() == '')
return false;
});
Using JQuery validate plugin can be much help. You can control the way plugin works from your HTML code and even not write any javascript! If you need more complex validatio, you can extend it by adding specific validation functions. It allows you to localize the application as well.
This page gives a good example on how to use the plugin: http://jquery.bassistance.de/validate/demo/milk/ (click the "Show script used on this page" link).
Here is a rudimentary fiddle, that you can use to validate your form, Just add a span after each of the fields that you need to validate.
http://jsfiddle.net/refhat/h2S6G/35/
I thought about this too, but the plugin can be a bit difficult to
use. Do you know if it allows to display an alert box when an error is
found, instead of the actual displaying on the page? That's a bit too
much for this form. Thanks a lot
Here's a validator I wrote that uses a pop-up style alert box for error messages. Is that the sort of thing you are after?
http://validator.codeplex.com/
Do you want default error messages like for required validator? Regarding jquery validate plugin was it the syntax it offers to place validation information in the method call you found difficult since for a large form having validation information located separately from the text boxes makes it harder to go through and verify all fields have the right validators and messages?

Categories