Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Allowing apostrophes in the HTML input field

Tags:

java

regex

I have a php code as shown below which validates the answer at Line A which user enters in a html form.

When user enters any answer with apostrophe in the html input field form, I am getting the error message Secret Answer is Invalid. For example: On entering Hello World', I am getting the error message Secret Answer is Invalid from Line Z.

//response
$response_error = new error();
$response_error->field = SECRET_response;
if($response != "" && $service->validAnswer($answer) != 'true'){   // Line A
    $response_error->inError = true;
    $response_error->errorMessage = SECRET_response.ISINVALID; // Line Z
} else {
    $response_error->inError = false;
}

The Java code/method belonging to the validAnswer method used at Line A above is:

public static boolean validAnswer(String answer) {
    Pattern a = Pattern.compile("^(?=.*\\S)[a-zA-Z0-9éèàêâçîëïÇÉÔÂÊÎÔÛËÏÀùÙ!#%&$%*\\- ]+$"); // Line B
    Matcher b = a.matcher(answer);

    logger.info("validAnswer: mmatches(): " + (b.matches()) + " a: " + a);

    return b.matches();
}  

Problem Statement:

I am wondering what changes I need to make in the java code above so that it takes apostrophe in the html input form.

This is what I have tried in the Java code:
I have put ' in at the end of [ ] inside of it. On trying that, it doesn't seem to work.

public static boolean validAnswer(String answer) {
    Pattern a = Pattern.compile("^(?=.*\\S)[a-zA-Z0-9éèàêâçîëïÇÉÔÂÊÎÔÛËÏÀùÙ!#%&$%*\\-' ]+$"); // Line A
    Matcher b = a.matcher(answer);

    logger.info("validAnswer: mmatches(): " + (b.matches()) + " a: " + a);

    return b.matches();
}  
like image 894
flash Avatar asked Sep 12 '25 06:09

flash


1 Answers

Calling Java from PHP just to use a regex is very weird and inefficient. PHP has regex support of course, so you don't need Java for that.

Anyway, your latest code works perfectly:

import java.util.regex.*;

public class Test
{
    public static boolean validAnswer(String answer)
    {
        Pattern a = Pattern.compile("^(?=.*\\S)[a-zA-Z0-9éèàêâçîëïÇÉÔÂÊÎÔÛËÏÀùÙ!#%&$%*\\-' ]+$");
        Matcher b = a.matcher(answer);
        return b.matches();
    }

    public static void main(String args[])
    {
        System.out.println(validAnswer("Hello World'"));
    }
}

Output:

true

So I guess you didn't recompile your code after modifying it.

like image 70
Olivier Avatar answered Sep 13 '25 20:09

Olivier