Spring Validation using Annotation #RegExp - spring

Im using Spring form validation to validate the input fields entered by the user. I need help to include space in a particular field. Below is the validation annotation that Im using. But it does not seem to allow space.
#RegExp(value="([0-9|a-z|A-Z|_|$|.])*",message="value can contain only digits,alphabets or _ or . or $")
private String cName ;
I would like to know what value I need to include in the validation annotation to include space in the name
I tried to include '\s' in the exp value to include blank space. But it doesn't seem to work
Any help on this is much appreciated.

Your regex String is not valid for your requirement.
Use the following regex instead:
//([0-9|a-z|A-Z|\\_|\\$|\\.|\\s])+
#Test
public void testRegex() {
String r = "([0-9|a-z|A-Z|\\_|\\$|\\.|\\s])+";
assertTrue("Allows space", Pattern.matches(r, "test test"));
assertTrue("Allows .", Pattern.matches(r, "12My.test"));
assertTrue("Allows _", Pattern.matches(r, "My_123"));
assertTrue("Allows $", Pattern.matches(r, "$ 1.0"));
}

Related

Freemarker template value missing while first or second letter is capitalized

I am trying to learn how to integrate Spring Boot(2.6.3) with FreeMarker(2.3.31). Everything works fine until I met an FreeMarker error while trying to get the value like ${myObject.pAram!} while the first or second letter of the param is capitalized.
So I did so test work and get the following conclusion:
While param name of an object is first letter or second letter capitalized, FreeMarker couldn`t get the param value. Some code here in case of my poor English:
#Data
public class TestBean {
String param; //no-capitalized param
String aParam; //second letter capitalized param
String Bparam; //first letter capitalized param
String cpRam; //third letter capitalized param
}
Here what I do some setter in controller:
#RequestMapping("/test")
public String insure(#PathVariable String module,HttpServletRequest request) {
TestBean testBean = new TestBean();
testBean.setParam("param-no capitalize");
testBean.setAParam("aParam-capitalize the second letter");
testBean.setBparam("Bparam-capitalize the first letter");
testBean.setCpAram("cpAram-capitalize the third letter");
request.setAttribute("testBean",testBean);
return "test";
}
And what the test.ftl looks like:
<body>
<body>
<div>${testBean.param!"missing param"}</div>
------------------------------
<div>${testBean.aParam!"missing aParam"}</div>
------------------------------
<div>${testBean.Bparam!"missing Bparam"}</div>
------------------------------
<div>${testBean.cpAram!"missing cpAram"}</div>
However, the final html result is:
param-no capitalize
------------------------------
missing aParam
------------------------------
missing Bparam
------------------------------
cpAram-capitalize the third letter
Since I`m new to FreeMarker and Spring Boot, I failed to figure out why.
Could someone tell me the exact reason? Am I missing some point?
Thanks a lot!
The Java Bean property names are deduced from the getter method names, not from the field names.
For Bparam, Lombok will generate getBparam(), which is the same that you will get for a filed named bparam. So the two cases are indistinguishable, and both will give the property name bparam.
For aParam, Lombok will generate getAParam(), which is the same that you will get for a filed named AParam. So the two cases are indistinguishable, and both will give the property name AParam. Now this last is not intuitive (I would rather expect aParam), but these are the rules of Java Beans (not of FreeMarker). Which, in turn is a consequence of the broken camel case conventions of Java (i.e., that you must keep letters that were originally upper case as upper case, instead of only using upper case for the first letter of words, so Java camel case is not reversible in general).

How to make Get Request with Request param in Postman

I have created an endpoint that accepts a string in its request param
#GetMapping(value = "/validate")
private void validateExpression(#RequestParam(value = "expression") String expression) {
System.out.println(expression);
// code to validate the input string
}
While sending the request from postman as
https://localhost:8443/validate?expression=Y07607=Curr_month:Y07606/Curr_month:Y07608
// lets say this is a valid input
console displays as
Y07607=Curr_month:Y07606/Curr_month:Y07608 Valid
But when i send
https://localhost:8443/validate?expression=Y07607=Curr_month:Y07606+Curr_month:Y07608
//which is also an valid input
console displays as
Y07607=Curr_month:Y07606 Curr_month:Y07608 Invalid
I am not understanding why "+" is not accepted as parameter.
"+" just vanishes till it reaches the api! Why?
I suggest to add this regular expression to your code to handle '+' char :
#GetMapping(value = "/validate")
private void validateExpression(#RequestParam(value = "expression:.+") String expression) {
System.out.println(expression);
// code to validate the input string
}
I didn't find any solution but the reason is because + is a special character in a URL escape for spaces. Thats why it is replacing + with a " " i.e. a space.
So apparently I have to encode it from my front-end
Its wise to encode special characters in a URL. Characters like \ or :, etc.
For + the format or value is %2. You can read more about URL encoding here. This is actually the preferred method because these special characters can sometimes cause unintended events to occur, like / or = which can mean something else in the URL.
And you need not worry about manually decoding it in the backend or server because it is automatically decoded, in most cases and frameworks. In your case, I assume you are using Spring Boot, so you don't need to worry about decoding.

What is use of '%s' in xpath

I have tried to know the reason in online but i didnt get it.
I want to know the reason why '%s' used in xpath instead of giving text message
I hope some one can help me on this.
see my scenario:
By.xpath(("//div[contains(text(),'%s')]/following-sibling::div//input"))
It's called wildcard.
E.g. you have
private final String myId = "//*[contains(#id,'%s')]";
private WebElement idSelect(String text) {
return driver.findElement(By.xpath(String.format(myId, text)));
}
Then, you can make a function like:
public void clickMyId(idName){
idSelect(idName.click();
}
And call
clickMyId('testId');
The overall goal of the %s is not using the string concatenation, but to use it injected into a string.
Sometimes, there are many locators for web elements which are of same kind, only they vary with a small difference say in index or String.
For e.g., //div[#id='one']/span[text()='Mahesh'] and
//div[#id='one']/span[text()='Jonny']
As it can been seen in the above example that the id is same for both the element but the text vary.
In that case, you can use %s instead of text. Like,
String locator = "//div[#id='one']//span[text()='%s']";
private By pageLocator(String name)
{
return By.xpath(String.format(locator, name));
}
So in your case,
By.xpath(("//div[contains(text(),'%s')]/following-sibling::div//input"))
the text is passed at runtime as only the text vary in the locator.
'%s' in XPath is used as String Replacement.
Example:
exampleXpath = "//*[contains(#id,'%s')]"
void findElement(String someText)
{
driver.findElement(By.xpath(String.format(exampleXpath, someText)));
}
So it will replace %s with someText passed by user.

String value with double quote in C#

I was trying to do autocomplete for my input box. When user start typing "I, then I should exactly search the keyword what user has typed ("I). When keys pressed, I was getting the string value as "\"I. How can i do the search based on what user has entered without stripping off any character from the string. Pls provide me any suggestion to help my issue.
Sample Code
public JsonResult AutoBibs(string searchTerm)
{
model = (from line in db.BibContents
where (line.Value.StartsWith(searchTerm) || line.Value.Contains(" " + searchTerm))
select new PoDetails
{
BibId = line.BibId
}).ToList();
return model;
}
The " always appends with an Escape character while processing the String variables in C# i.e. it appends "\" at the beginning. It would not change your functionality and you can still continue with your Auto Complete feature. Generally you can find this during in DEBUG mode only.
Read this MSDN article for more details.

How to check if a property constains a space in groovy?

I am new to grails, and I am having a problem on how to write the proper constraints of one of the properties of my class. I want to check if the input contains a space (' '). Here is my code..
static constraints = {
username nullable: false, blank: false, minSize: 6, matches: /[A-za-z0-9_]{6,}/, validator: {
Account.countByUsername(it) < 1
}
Please help me.
Thanks!
You would want to use a custom validator like:
username validator: { val -> if (val.contains(' ')) return 'value.hasASpace' }
Edit: As R. Valbuena pointed out, you would need to change your countByUsername() validator to a unique: true.
In addition to a custom validator, you can also use the matches validator to ensure that only valid characters are used.
It looks like you're using this in your original question and the regex you're using doesn't allow a space, so a username with a space should fail that validator.
If you want to give a special message to someone if they have a space in it (instead of some other invalid character), then doelleri's answer is the right way to do that.

Resources