Regex Text Input Validation - regex

I'm way in over my head here, but trying to learn.
Attempting to use text input validation on Cognito forms by way of a custom regular expression.
I'm trying to capture users work email in an online form. In the "work email" field they would only be able to enter the text to the left of the # and then once they type "#" it'll automatically populates the "organization.com." I'll probably want to make sure that the user cant enter spaces, and other characters (ie:'*&^%$#!)
Been googling how to do this but no luck so far. I'm sure I'm using the wrong terminology to describe what i'm trying to accomplish.

This does everything you need except handle the actual submission of the data.
document.querySelector('input').oninput = function () {
if (this.value.endsWith('#')) {
this.value += 'organization.com';
}
}
<form>
<input type=email pattern=.*#organization\.com$ title='name#organization.com' required />
<button type=submit>Submit</button>
</form>

Related

Angular2 - Why does my reactive form input with an html pattern attribute is not validating correctly?

I'm struggling with a problem that I can't understand:
I need to validate an input field with a pattern="[0-9]+([,.][0-9])?" attribute on an angular reactive form with Validators.pattern, but it seems my ? quantifier at the end is not working...
What I want
I want to validate numbers with zero or one decimal maximum. As you can see on https://regex101.com/r/2D2sww/1, the regex is working great.
The actual problem
In my app I can enter as many decimals as I want without the Validator.pattern to do anything. Any other character invalidate the form, so my Validator is working.
Here is my code (simplified):
component.html
<form [formGroup]="myForm">
<input type="number" formControlName="myInputField" id="myInputField" pattern="[0-9]+([,.][0-9])?" required />
</form>
component.ts (Every import and declarations are skipped for clarity)
ngOnInit() {
this.myForm = this.formBuilder.group({
myInputField: [
"",
[Validators.required, Validators.pattern],
]
});
}
I already tried to use Validators.pattern(/^[0-9]+([,.][0-9])?$/) and Validators.pattern("[0-9]+([,.][0-9])?") as pointed in the documentation, but it doesn't change anything, so I suspect my Regex to be incorrect...
Any ideas ? Thanks, have a nice day :)
I think there is nothing wrong with your validator pattern regex,
you can remove the pattern's attribute from the input, it is redundant because you are initiating it from inside the ts file: 'myInputField': new FormControl(null, [Validators.pattern('^[0-9]+([,.][0-9])?$')]).
StackBlitz

Primeng KeyFilter not working well

i am using KeyFilter Module of primeng here is my code :
<input type="text" pInputText [(ngModel)]="price.TintCost" [pKeyFilter]="patternDecimal" name="tintCost" required="true" />
here is my typescrip code :
patternDecimal: RegExp = /^[0-9]+(\.[0-9]{1,2})?$/;
and here is version of primeng :|
"primeng": "^5.2.0-rc.1",
i tested in regex then i can type dot(.) but when i apply to KeyFilter, it doesn't allow the dot(.). Someone help me, please
I solved this problem by adding a mask as default
KeyFilter.DEFAULT_MASKS['currencyRegex'] = /^-?(?:0|[1-9]\d{0,2}(?:,?\d{3})*)(?:\.\d+)?$/;
I solved this problem by change the pValidateOnly property to true.
The problem is that the KeyFilter check any press on keyboard and if the complete value is no the correct, then dont permit write, just if you copy and paste the value.
In the documentation say
Instead of blocking a single keypress, the alternative validation mode
which is enabled with pValidateOnly property validates the whole input
with a built-in Angular validator.
https://www.primefaces.org/primeng-6.1.6/#/keyfilter
Example that work for me.
Component.ts
public twoDecimal: RegExp = /^\s*-?(\d+(\.\d{1,2})?|\.\d{1,2})\s*$/
Component.html
<input name="decimalField"
#decimalField="ngModel"
[pKeyFilter]="twoDecimal"
[pValidateOnly]="true"
[(ngModel)]="item.decimalField"
type="text" pInputText>
<div *ngIf="!decimalField.valid" class="alert alert-danger">
<p>Incorrect format.</p>
</div>
The answer of #Norberto Quesada is correct.
Without pValidateOnly the regex will validate on every key stroke.
Let's say you want to enter the value "47.11":
You begin to enter "4" => this would be valid, no input blocked.
Same for "47"
As soon as you enter "47. => validation fails, input blocked.
I was thinking maybe it's possible to enter "4711" first and then the "." in between but for some reason this doesn't seem to work, too... Maybe this is a bug?
Anyways, you can take a look at this stackblitz example for better understanding.
I've also prepared an example of using ValidateOnly and in addition to that restrict the input to only numbers using keyDown event

how to set input regex pattern that matches everything EXCEPT empty string and 'Enter Code'

I have to use a legacy library to emulate html5 placeholder instead of actually using the placeholder attribute. We're using a js library that emulates this by populating the input's value, then clears the value when user clicks on the input. For example we have a captcha that has a temporary value of 'Enter Code'. We would still like to use HTML5 tooltip validations for browsers that can support it. So if the form is submitted without the captcha filled in than the tooltip should read 'Please enter code'. I set the 'required' attribute on the captcha text input field, however, this doesn't work because the js library set the value of the input field so that it's not blank. And the form is submitting anyway.
I would like to specify a pattern on the captcha input field so that the string 'Enter Code' is not valid, and neither is empty string.
I have tried:
<input id="captcha" type="text" required="required" pattern="(?!Enter Code)">
But that doesn't seem to work.
Use regex pattern ^(?!Enter Code$).+
<input id="captcha" type="text" required="required" pattern="^(?!Enter Code$).+">

Add a newline after each closing html tag in web2py

Original
I want to parse a string of html code and add newlines after closing tags + after the initial form tag. Here's the code so far. It's giving me an error in the "re.sub" line. I don't understand why the regex fails.
def user():
tags = "<form><label for=\"email_field\">Email:</label><input type=\"email\" name=\"email_field\"/><label for=\"password_field\">Password:</label><input type=\"password\" name=\"password_field\"/><input type=\"submit\" value=\"Login\"/></form>"
result = re.sub("(</.*?>)", "\1\n", tags)
return dict(form_code=result)
PS. I have a feeling this might not be the best way... but I still want to learn how to do this.
EDIT
I was missing "import re" from my default.py. Thanks ruakh for this.
import re
Now my page source code shows up like this (inspected in client browser). The actual page shows the form code as text, not as UI elements.
<form><label for="email_field">Email:</label>
<input type="email" name="email_field"/><label
for="password_field">Password:</label>
<input type="password" name="password_field"/><input
type="submit" value="Login"/></form>
EDIT 2
The form code is rendered as UI elements after adding XML() helper into default.py. Thanks Anthony for helping. Corrected line below:
return dict(form_code=XML(result))
FINAL EDIT
Fixing the regex I figured myself. This is not optimal solution but at least it works. The final code:
import re
def user():
tags = "<form><label for=\"email_field\">Email:</label><input type=\"email\" name=\"email_field\"/><label for=\"password_field\">Password:</label><input type=\"password\" name=\"password_field\"/><input type=\"submit\" value=\"Login\"/></form>"
tags = re.sub(r"(<form>)", r"<form>\n ", tags)
tags = re.sub(r"(</.*?>)", r"\1\n ", tags)
tags = re.sub(r"(/>)", r"/>\n ", tags)
tags = re.sub(r"( </form>)", r"</form>\n", tags)
return dict(form_code=XML(tags))
The only issue I see is that you need to change "\1\n" to r"\1\n" (using the "raw" string notation); otherwise \1 is interpreted as an octal escape (meaning the character U+0001). But that shouldn't give you an error, per se. What error-message are you getting?
By default, web2py escapes all text inserted in the view for security reasons. To avoid that, simply use the XML() helper, either in the controller:
return dict(form_code=XML(result))
or in the view:
{{=XML(form_code)}}
Don't do this unless the code is coming from a trusted source -- otherwise it could contain malicious Javascript.

This regex does not work in Chrome

Hi i just put up a validation function in jScript to validate filename in fileupload control[input type file]. The function seems to work fine in FF and sometimes in ie but never in Chrome. Basically the function tests if File name is atleast 1 char upto 25 characters long.Contains only valid characters,numbers [no spaces] and are of file types in the list. Could you throw some light on this
function validate(Uploadelem) {
var objRgx = new RegExp(/^[\w]{1,25}\.*\.(jpg|gif|png|jpeg|doc|docx|pdf|txt|rtf)$/);
objRgx.ignoreCase = true;
if (objRgx.test(Uploadelem.value)) {
document.getElementById('moreUploadsLink').style.display = 'block';
} else {
document.getElementById('moreUploadsLink').style.display = 'none';
}
}
EDIT:
Nope still does not seem to work , i am using IE 8(tried all the compatibility modes), Chrome v8.0, FF v 3.6.
Here is a html snippet in which i wired up the validate function,
<div>
<input type="file" name="attachment" id="attachment" onchange="validate(this)" />
<span class="none">Filename should be within (1-25) letters long. Can Contain only letters
& numbers</span>
<div id="moreUploads">
</div>
<div id="moreUploadsLink" style="display: none;">
Attach another File</div>
</div>
It works perfectly for me. How do you call the validate function ? – M42
You tried this on Google Chrome and IE 8 ? i added HTML Snippet in where in i used all of the recommended regX. No Clues as to why doesn't work!!
Mike, i am unable to comment your post here So this is for you.
The Validation Fails for which ever file i choose in the html input. I Also wired the validation in onblur event but proves same. The validate function will mimic the asp.net regular expression validator which displays validation error message when regular expression is not met.
Try simplifying your code.
function validate(Uploadelem) {
var objRgx = /^[\w]{1,25}\.+(jpg|gif|png|jpeg|doc|docx|pdf|txt|rtf)$/i;
if (objRgx.test(Uploadelem.value)) {
document.getElementById('moreUploadsLink').style.display = 'block';
} else {
document.getElementById('moreUploadsLink').style.display = 'none';
}
}
Your specification is hazy, but it appears that you want to allow dots within filenames (in addition to the dot that separates filename and extension).
In that case, try
var objRbx = /^[\w.]{1,25}\.(jpg|gif|png|jpeg|doc|docx|pdf|txt|rtf)$/i;
This allows filenames that consist only of the characters a-z, A-Z, 0-9, _ and ., followed by a required dot and one of the specified extensions.
As far as I know, Chrome adds a path in front of the filename entered, so you have just to change your regex from:
/^[\w]{1,25}\.*\.(jpg|gif|png|jpeg|doc|docx|pdf|txt|rtf)$/
to:
/\b[\w]{1,25}\.+(jpg|gif|png|jpeg|doc|docx|pdf|txt|rtf)$/
SOLVED
Primary reason that all [CORRECT regx pattern] did not work is Different browsers returned different values for HTML File Input control.
Firefox: Returns the File Upload controls FileName {As Expected}
Internet Explorer: Returns the Full Path to the File from Drive to File [Pain in the Ass]
Chrome: Returns a fake path as [C:\FakePath\Filename.extension]
I got a solution to the thing for chrome and FF but not IE.
Chrome and Firefox:
use FileUploadControlID.files[0].fileName or FileUploadControlID.files[0].name
IE
Again biggest pain in the ass [someone suggest a solution]
Valid Regex to Validate both fileName and Extension would be:
/\b([a-zA-Z0-9._/s]{3,50})(?=(\.((jpg)|(gif)|(jpeg)|(png))$))/i
1.File Nameshould be between 3 and 50 characters
2. Only jpg,gif,jpeg,png files are allowed