I am making a function to validate form input data (for practice) and maybe i'll also use it.
I was wondering if there is some way to apply the same functionality without eval as i have heard that it is bad on the js interpreter. Also improvements, if any. And also i would like to know if there is something that does the same job, ie, to apply reusable regex rules to input fields.
Here is my JavaScript validation function.
function validate(){
var num=/[0-9]+/g;
var alphanum=/[0-9a-zA-Z_]+/g;
var alphanumSpace=/[0-9a-zA-Z\w_]+/g;
var alpha=/[a-zA-Z]+/g;
var alphaSpace=/[a-zA-Z\w]+/g;
var alphanumDot=/[0-9a-zA-Z\._]+/g;
var money=/[0-9]+\.?[0-9]{0,2}?/g;
var flag=true;
var alertBox="Incorrect entries:\n\n";
$.each($('input[data-check]'),function(index,value){
if(!eval(value.dataset.check+'.test("'+value.value+'")')){
alertBox+=value.name+",\n";
flag=false;
}
});
alert(alertBox);
return flag;
}
Which is used to call on a form as
<form onsubmit="return validate()">
On fields that have the data-check attribute as any of the matching variables that i have defined as
<input data-check='num'>
This will call the test the regex against the num regex as defined in my code.
You can do something like this using new RegExp and window[]:
$.each($('input[data-check]'),function(index,value){
var str = value.value;
var patt = new RegExp(window[value.dataset.check]);
var res = patt.test(str);
if(!res){
alertBox+=value.name+",\n";
flag=false;
}
});
Related
This a function that allows people to type only English characters and numbers in a text field. Basically I need to update this function and allow to type in symbols too. I don't know anything about javascript function and I would appreciate if someone could send me the updated function. I know it might be really easy to do it if I knew how to code 🙃
Is there anyone who can help? Thank you
function add_js_code() {
echo "<script>jQuery('.wc-pao-addon-wrap input[type=\"text\"], .wc-pao-addon-wrap textarea').keyup(function(){
var input_val = jQuery(this).val();
var inputRGEX = /^[a-zA-Z0-9]*$/;
var inputResult = inputRGEX.test(input_val);
if(!(inputResult))
{
this.value = this.value.replace(/[^a-z0-9\s]/gi, '');
}
});</script>";
}
add_action( 'wp_footer', 'add_js_code' );
Replace your regex
FROM
var inputRGEX = /^[a-zA-Z0-9]*$/;
TO
var inputRGEX = /^[a-zA-Z0-9!##\$%\^\&*\)\(+=._-]/;
You can also modify the
I've tested the three of the regex's on http://www.regexpal.com/ and they are what I need, but when doing a regex test 2 of them return false (BTC and CAD) and only the Bitcoin address seems to work (you may test with this wallet below).
13dHNxtbckAFM4PzdBqWgymFJmcv3Yzi32
https://jsfiddle.net/ps2fj1ff/1
(all the relevant code is in the html section)
var regWallet = new RegExp("^[13][a-km-zA-HJ-NP-Z1-9]{25,34}$");
var regBTC = new RegExp("^\d*\.\d*$");
var regCAD = new RegExp("^\d+(\.(\d{2}))?$");
$('#button1').on('click', function() {
var btcCheck = $('#amount_btc').val();
if (regBTC.test(btcCheck)) {
} else {
alert("Invalid BTC value!");
}
var cadCheck = $('#amount_cad').val();
if (regCAD.test(cadCheck)) {
} else {
alert("Invalid CAD value!");
}
var walletCheck = $('#wallet').val();
if (regWallet.test(walletCheck)) {
} else {
alert("Invalid Bitcoin address, please make sure you've entered a valid address!");
}
});
The reason is that in var regBTC = new RegExp("^\d*\.\d*$"); the \ is used to escape the character so if you console.log(regBTC) you will see it as ^d*.d*$.
To prevent this you will have to double escape it: var regBTC = new RegExp("^\\d*\\.\\d*$");
Or better yet use / instead: var regBTC = /^\d*\.\d*$/;
The same goes for the other regex too.
(I initially thought single quote would work too, but apparently not in javascript)
Use this instead:
var regBTC = /^\d*\.\d*$/;
var regCAD = /^\d+(\.(\d{2}))$/;
It's cleaner and more readable as most editors will give you regexp syntax highlighting in this format.
There really isn't any good reason to use new RegExp which forces you to write the expression as a string, which forces you to use confusing escapes, when there is a proper regular expression syntax built into JavaScript.
Im trying to implement a validation for an input field in IBM BPM.
Im not really familiar with java script but I try to get method that returns
ture if a string contains any numbers.
awdadw = valid
awdawd2d = invalid
I tried this method:
function hasNumbers(t)
{
var pattern=new RegExp("^[A-Za-z]+$");
return pattern.test(t); // true if string. Returns false for numbers
}
When I try this function, it says that method / variable RegExp is unknown. Since it is rather basci stuff I hope to get some sources where this topic is explained.
You can use this:
function validate(){
var re = /^[A-Za-z]+$/;
if(re.test(document.getElementById("inputID").value))
alert('Valid Name.');
else
alert('Invalid Name.');
}
Based on adre3wap this worked for me:
function validate(t){
var re = /^[A-Za-z]+$/;
if(re.test(t))
return false;
else
return true;
}
i want javascript code to check whether my input text is in specific format as AS0301-12345
<apex:inputText id="searchText" value="{!searchText}" onmousemove="checkingstring(this)"/>
<script>
function checkingstring(searchText){
var pattern = "([a-zA-Z](2)[0-9](4)-[0-9](5))"; /// is it correct
var regexp = new System.Text.RegularExpressions.Regex(pattern);
var userInput = "(123) 555-1243";
if (!regexp.IsMatch($component.searchText))
{
alert("The syntax is always as follows: AANNNN-NNNNN (A= Alpha/Letter; N= Number) i.e.FL0301-12345</b>");
}
}
</script>
Your JS function should look more like this:
function checkingstring(inputElem) {
var regex = /^[A-Z]{2}[0-9]{4}-[0-9]{5}$/i;
var searchText = inputElem.value;
if (searchText.length && !regex.test(searchText)) {
alert('The syntax is always as follows: AANNNN-NNNNN \n' +
'(A: Alpha/Letter; N: Number), e.g. FL0301-12345');
}
}
You should probably also change the onmousemove to something more meaningful, like onblur maybe.
Take a look at this short demo.
This is how I'd do it. There is a lot of functionality you can squeeze into shorthand. Changed onMouseMove to onChange so instead of checking whenever the mouse moves it should check when an edit of searchText completes.
<apex:inputText id="searchText" value="{!searchText}" onChange="checkingstring(this)"/>
<script>
function checkingstring(searchText){
var regexp = /^[A-Z]{2}\d{4}-\d{5}$/i; //AANNNN-NNNNN A = Capital N = Number
if (!regexp.exec(searchText.value)) {
alert("The syntax is always as follows: AANNNN-NNNNN (A= Alpha/Letter; N= Number) i.e.FL0301-12345</b>");
}
}
</script>
got some ideas from w3schools js regexp page.
I would like to find difference between two fields using JavaScript in iText.
I am able to find the sum of them using below code:
PdfStamper stamperResult = new PdfStamper(readersectionResult, new FileOutputStream(RESULT_NEW));
stamperResult .addJavaScript("var nameField = this.getField(\"total\");"+ "nameField.setAction(\"Calculate\",'AFSimple_Calculate(\"SUM\",\"total1\", \"total2\")')");
Is there any way to find the difference using 'AFSimple_Calculate' similar to what I did in the above code snippet?
Thanks for editing! I tried your suggestion but it does not seem to work for some reason.
stamperResult.addJavaScript(" var total1 = this.getField(\"value1\"); var total2 = this.getField (\"value2\"); var subtr = this.getField(\"total\"); subtr.value = total1.value - total2.value;");
I separated newlines by spaces and added right escape characters.
I was also thinking of using a different logic for subtraction using AF methods : like this
stamperResult.addJavaScript("var nameField = this.getField(\"total\");"+ "nameField.setAction(\"Calculate\",'AFSimple_Calculate(\"SUM\",\"total1\", \"-total2\")')");
In the above code I was trying to add -(negative value) to total 2 so that it will be subtracted from total1 though the AF method is still 'SUM'.
But that does not work.
The below simple code seem to work :
stamperResult.addJavaScript("var nameField = this.getField('total');" +
"nameField.setAction('Calculate'," +
"'subtract()');" +
"" +"function subtract(){this.getField('total').value
= (this.getField('total_1').value -this.getField('total_2').value); }");
I updated your question because it contained many spelling errors. I didn't edit the code snippet because I don't know what the original code snippet is like. In any case: I think something went wrong during the copy/paste process, as I don't think your code snippet compiles in its current state.
In any case: as far as I know the AF-methods (the AF stands for Adobe Forms) may not be present in every viewer, and as far as I know Adobe didn't implement a way to subtract values from each other in the AFSimple_Calculate method.
For these two reasons, you may prefer regular JavaScript instead of using a pre-canned function that may or may not be pre-canned.
This regular JavaScript may look like this:
var total1 = this.getField("total1");
var total2 = this.getField("total2");
var subtr = this.getField("difference");
subtr.value = total1.value - total2.value;
I'm not sure if that answers your question. Maybe you just want:
var total1 = this.getField("total1");
var total2 = this.getField("total2");
var namefield = total1.value - total2.value;
You can put these lines inside a String using the right escape characters and replacing the newlines by spaces or newline characters.
Of course, you need to trigger this code somewhere. Below you'll find an example that puts the negative value of the content of a value1 field into a value2 field.
public static void main(String[] args) throws IOException, DocumentException {
Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("js.pdf"));
document.open();
writer.addJavaScript("function makeNegative() { this.getField('value2').value = -(this.getField('value1').value); } ");
Rectangle rect1 = new Rectangle(40, 740, 200, 756);
TextField value = new TextField(writer, rect1, "value1");
value.setBorderColor(GrayColor.GRAYBLACK);
value.setBorderWidth(0.5f);
PdfFormField field = value.getTextField();
field.setAdditionalActions(PdfName.BL, PdfAction.javaScript("makeNegative();", writer));
writer.addAnnotation(field);
Rectangle rect2 = new Rectangle(40, 710, 200, 726);
TextField neg = new TextField(writer, rect2, "value2");
neg.setBorderColor(GrayColor.GRAYBLACK);
neg.setBorderWidth(0.5f);
writer.addAnnotation(neg.getTextField());
document.close();
}
Note that I used a Blur action. This means the method will be triggered as soon as you select another field after filling out the value1 field.